#!/bin/bash

set -e

# Parse command line arguments
TARGET="$1"  # Optional target parameter

# Validate target if provided
if [[ -n "$TARGET" ]] && [[ ! "$TARGET" =~ ^(stable|latest|[0-9]+\.[0-9]+\.[0-9]+(-[^[:space:]]+)?)$ ]]; then
    echo "Usage: $0 [stable|latest|VERSION]" >&2
    exit 1
fi

# 只使用腾讯云COS作为下载源
TENCENT_COS_BASE="https://claudecode-1301368149.cos.ap-guangzhou.myqcloud.com/claude-mirror"
DOWNLOAD_SOURCES=("$TENCENT_COS_BASE")
DOWNLOAD_DIR="$HOME/.claude/downloads"

# Check for required dependencies
DOWNLOADER=""
if command -v curl >/dev/null 2>&1; then
    DOWNLOADER="curl"
elif command -v wget >/dev/null 2>&1; then
    DOWNLOADER="wget"
else
    echo "Either curl or wget is required but neither is installed" >&2
    exit 1
fi

# Check if jq is available (optional)
HAS_JQ=false
if command -v jq >/dev/null 2>&1; then
    HAS_JQ=true
fi

# Download function that works with both curl and wget
download_file() {
    local url="$1"
    local output="$2"
    
    if [ "$DOWNLOADER" = "curl" ]; then
        if [ -n "$output" ]; then
            curl -fsSL -o "$output" "$url"
        else
            curl -fsSL "$url"
        fi
    elif [ "$DOWNLOADER" = "wget" ]; then
        if [ -n "$output" ]; then
            wget -q -O "$output" "$url"
        else
            wget -q -O - "$url"
        fi
    else
        return 1
    fi
}

# 从腾讯云COS下载
download_from_cos() {
    local file_path="$1"
    local output_file="$2"
    local full_url="$TENCENT_COS_BASE/$file_path"

    if [ -n "$output_file" ]; then
        # 下载到文件
        if download_file "$full_url" "$output_file"; then
            return 0
        else
            return 1
        fi
    else
        # 输出到标准输出
        if download_file "$full_url" ""; then
            return 0
        else
            return 1
        fi
    fi
}

# Simple JSON parser for extracting checksum when jq is not available
get_checksum_from_manifest() {
    local json="$1"
    local platform="$2"
    
    # Normalize JSON to single line and extract checksum
    json=$(echo "$json" | tr -d '\n\r\t' | sed 's/ \+/ /g')
    
    # Extract checksum for platform using bash regex
    if [[ $json =~ \"$platform\"[^}]*\"checksum\"[[:space:]]*:[[:space:]]*\"([a-f0-9]{64})\" ]]; then
        echo "${BASH_REMATCH[1]}"
        return 0
    fi
    
    return 1
}

# Detect platform
case "$(uname -s)" in
    Darwin) os="darwin" ;;
    Linux) os="linux" ;;
    *) echo "Windows is not supported" >&2; exit 1 ;;
esac

case "$(uname -m)" in
    x86_64|amd64) arch="x64" ;;
    arm64|aarch64) arch="arm64" ;;
    *) echo "Unsupported architecture: $(uname -m)" >&2; exit 1 ;;
esac

# Check for musl on Linux and adjust platform accordingly
if [ "$os" = "linux" ]; then
    if [ -f /lib/libc.musl-x86_64.so.1 ] || [ -f /lib/libc.musl-aarch64.so.1 ] || ldd /bin/ls 2>&1 | grep -q musl; then
        platform="linux-${arch}-musl"
    else
        platform="linux-${arch}"
    fi
else
    platform="${os}-${arch}"
fi
mkdir -p "$DOWNLOAD_DIR"

# Determine version to download
if [[ -z "$TARGET" || "$TARGET" == "stable" || "$TARGET" == "latest" ]]; then
    # For stable/latest, get version from COS
    echo "获取版本信息..."
    if stable_version=$(download_from_cos "stable" 2>/dev/null); then
        # 清理版本号，移除可能的额外信息
        version=$(echo "$stable_version" | tr -d '\n\r\t ')
        if [ -z "$version" ]; then
            echo "Failed to get valid version from stable file" >&2
            echo "Please specify a version, e.g., $0 2.0.34" >&2
            exit 1
        fi
    else
        # If stable file doesn't exist, try to get version directory listing
        echo "Could not determine latest version automatically" >&2
        echo "Please specify a version, e.g., $0 2.0.34" >&2
        exit 1
    fi
else
    # Use specified version
    version="$TARGET"
fi

echo "Downloading Claude Code version: $version"
echo "Platform: $platform"

# 尝试下载校验和文件
echo "  获取校验和文件..."
temp_checksum_file="/tmp/claude_checksums_$$.txt"
checksums_content=""

echo "    校验和文件路径: $version/checksums.txt"
if download_from_cos "$version/checksums.txt" "$temp_checksum_file"; then
    checksums_content=$(cat "$temp_checksum_file")
    rm -f "$temp_checksum_file"
fi

if [ -n "$checksums_content" ]; then
    # Extract checksum for platform from checksums.txt (format: sha256  filename)
    checksum=$(echo "$checksums_content" | grep "claude" | cut -d' ' -f1)

    # Validate checksum format (SHA256 = 64 hex characters)
    if [ -z "$checksum" ] || [[ ! "$checksum" =~ ^[a-f0-9]{64}$ ]]; then
        echo "Warning: Could not find valid checksum for platform $platform" >&2
        echo "Proceeding without checksum verification" >&2
        checksum=""
    fi
else
    echo "Warning: No checksum file found, proceeding without checksum verification" >&2
    checksum=""
fi

# 下载二进制文件
echo "  下载二进制文件..."
binary_path="$DOWNLOAD_DIR/claude-$version-$platform"

echo "    二进制文件路径: $version/$platform/claude"
if ! download_from_cos "$version/$platform/claude" "$binary_path"; then
    echo "下载失败，请检查版本 $version 和平台 $platform 是否存在" >&2
    echo "下载源: 腾讯云COS ($TENCENT_COS_BASE)"
    rm -f "$binary_path"
    exit 1
fi

# Verify checksum if available
if [ -n "$checksum" ]; then
    # Pick the right checksum tool
    if [ "$os" = "darwin" ]; then
        actual=$(shasum -a 256 "$binary_path" | cut -d' ' -f1)
    else
        actual=$(sha256sum "$binary_path" | cut -d' ' -f1)
    fi

    if [ "$actual" != "$checksum" ]; then
        echo "Checksum verification failed" >&2
        echo "Expected: $checksum" >&2
        echo "Actual:   $actual" >&2
        rm -f "$binary_path"
        exit 1
    fi
    echo "Checksum verification passed"
else
    echo "Skipping checksum verification (no checksum available)"
fi

chmod +x "$binary_path"

# Run claude install to set up launcher and shell integration
echo "Setting up Claude Code..."
"$binary_path" install ${TARGET:+"$TARGET"}

# Clean up downloaded file
rm -f "$binary_path"

echo ""
echo "✅ Installation complete!"
echo ""
